package org.zebra.common.crypto;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhanghongbin
 */
public class RsaCryptoProvider implements CryptoProvider {

    /**
     * 公钥
     */
    private String publicKey = "";

    /**
     * 私钥
     */
    private String privateKey = "";

    public RsaCryptoProvider(String publicKey, String privateKey) {
        this.publicKey = publicKey;
        this.privateKey = privateKey;
    }

    @Override
    public String encrypt(String value) {
        RSA rsa = SecureUtil.rsa(null, publicKey);
        return rsa.encryptBase64(value, StandardCharsets.UTF_8, KeyType.PublicKey);
    }

    @Override
    public String decrypt(String value) {
        RSA rsa = SecureUtil.rsa(privateKey, null);
        return rsa.decryptStr(value, KeyType.PrivateKey, StandardCharsets.UTF_8);
    }

    public static Map<String, String> generateKey() {
        Map<String, String> keyMap = new HashMap<>(2);
        RSA rsa = SecureUtil.rsa();
        keyMap.put("privateKey", rsa.getPrivateKeyBase64());
        keyMap.put("publicKey", rsa.getPublicKeyBase64());
        return keyMap;
    }
}
